<?php
/**
 * 后台管理员表操作模型
 * @author lifw
 */
class MAdmin extends MY_Model {

	const IS_FORBIDDEN = 1;
	const NOT_FORBIDDEN = 0;
	
	protected $table = 'admins';
	private $filter = array();

    public static $GROUPTYPE = [
        '1'=>'销售组类型',
        '2'=>'测评组类型',
        '3'=>'财务组类型',
        '4'=>'人事组类型',
        '5'=>'采购组类型',
    ];

    function __construct() {

        parent::__construct();
    }

    
    public function getState($state = NULL){
    	$f = Array(self::NOT_FORBIDDEN=>'启用', self::IS_FORBIDDEN=>'禁用');
    	if($state === NULL){
    		return $f;
    	}
    	return element($state, $f, '');
    }

    public function getAllDistribution(){
        $this->db->select( $this->table.'.*');
        $this->db->distinct();
        $this->db->from($this->table);
        $this->db->where('role_id in (2,4)');
        if($this->_user->role_id == 2 || $this->_user->role_id == 4){
            $this->db->where('group_id',$this->_user->group_id);
        }

        $query = $this->db->get();
        $queryResult =  $query->result();
        $kvArr = array();
        foreach ($queryResult as $k=>$v){
            $kvArr[$v->id] = $v->name;
        }
        return $kvArr;
    }

    /**
     * 根据管理员ID查询管理员信息
     * @param $id 管理员ID
     */
	public function getById($id){
		$query = $this->db->where('id',$id)->get($this->table);
		return $query->row();
	}
	/**
	 * 根据管理员名查询管理员信息
	 * @param $name	管理员名（完全匹配）
	 */
	public function getByName($name){
		$query = $this->db->where('account',$name)->get($this->table);
		return $query->row();
	}

	public function getList($limit){
		$this->db->select('*');
		$this->db->from($this->table);
		$this->db->limit($limit['limit'],$limit['offset']);
		$this->formfilter->doFilter();
		$query = $this->db->get();
		return $query->result();
	}

	public function getGroupList($limit){
        $this->db->select('a.*,p.name as g_name,p.type as p_type');
        $this->db->from($this->table.' a');
        $this->db->join('admin_group p','p.id = a.group_id','LEFT');
        $this->db->limit($limit['limit'],$limit['offset']);
        $this->formfilter->doFilter();
        $this->db->where('a.forbidden',0);
        $query = $this->db->get();
        return $query->result();
    }

    public function getGroupCount(){
        $this->db->select('count(*) as num');
        $this->db->from($this->table.' a');
        $this->db->join('admin_group p','p.id = a.group_id','LEFT');
        $this->formfilter->doFilter();
        $this->db->where('a.forbidden',0);
        $tmp = $this->db->get()->result();
        return (int)$tmp[0]->num;
    }
	
	public function getCount(){
		$this->db->select('count(a.id) as num');
		$this->db->from($this->table.' a');
        $this->db->join('admin_group p','p.id = a.group_id','LEFT');
		$this->formfilter->doFilter();
        $this->db->where('a.forbidden',0);
		$tmp = $this->db->get()->result();
		return (int)$tmp[0]->num;
	}
	
	public function getLeaverList($limit){
		$this->db->select('a.*,count(distinct asin.id) asin_num,count(distinct emails.id) email_num');
		$this->db->from($this->table.' a');
		$this->db->join('asin asin','asin.creator_id = a.id','LEFT');
		$this->db->join('emails emails','emails.creator_id = a.id','LEFT');
		$this->db->limit($limit['limit'],$limit['offset']);
		$this->formfilter->doFilter();
		$this->db->where('forbidden',1);
		$this->db->group_by('a.id');
		$query = $this->db->get();
		return $query->result();
	}
	
	public function getLeaverCount(){
		$this->db->select('count(*) as num');
		$this->db->from($this->table.' a');
		$this->formfilter->doFilter();
		$this->db->where('a.forbidden',1);
		$tmp = $this->db->get()->result();
		return (int)$tmp[0]->num;
	}


	public function getChildrenAdmin($role_id,$group_id){
	    if ($role_id == 1){
            $this->db->select('a.id,a.account,p.name');
            $this->db->from($this->table.' a');
            $this->db->join('admin_group p','p.id = a.group_id','LEFT');
            $this->db->where('a.role_id in (2,4)');
            $this->db->where('a.forbidden','0');
            $queryResult = $this->db->get()->result();
            $kvArr = array();
            foreach ($queryResult as $k=>$v){
                $kvArr[$v->id] = $v->account.'—('.$v->name.')';
            }
            return $kvArr;
        }else if ($role_id == 2){
            $this->db->select('a.id,a.account,p.name');
            $this->db->from($this->table.' a');
            $this->db->join('admin_group p','p.id = a.group_id','LEFT');
            $this->db->where('a.group_id',$group_id);
            $this->db->where('a.forbidden','0');
            $queryResult = $this->db->get()->result();
            $kvArr = array();
            foreach ($queryResult as $k=>$v){
                $kvArr[$v->id] = $v->account.'—('.$v->name.')';
            }
            return $kvArr;
        }else{
	        return false;
        }
    }

	/**
	 * 得到所有账户管理员id=>account数组
	 * @return NULL[]
	 */
	public function getAllShopAdmin(){

        return $this->_getAdminsByGroupType(1); //1,销售组类型
	}

    public function getAllPurchaser(){

        return $this->_getAdminsByGroupType(5);
    }

	/**
	 * 得到所有测评管理员id=>account数组
	 * @return NULL[]
	 */
	public function getAllReviewsAdmin(){
        $this->db->select('a.id,a.account,a.name');
        $this->db->from($this->table.' a');
        $this->db->join('roles r','a.role_id = r.id and r.id in (2,3,4,5)','LEFT');
        $this->db->where('a.id <> 1 and a.id <> 28');
        $queryResult = $this->db->get()->result();
        $kvArr = array();
        foreach ($queryResult as $k=>$v){
            $kvArr[$v->id] = $v->account.'-'.$v->name;
        }
        return $kvArr;
	}
	/**
	 * 得到所有财务管理员id=>account数组
	 * @return NULL[]
	 */
	public function getAllFanceAdmin(){

        return $this->_getAdminsByGroupType(3); //3,财务组类型
	}


    /**
     * 根据管理组的类型返回对应的所有管理员，包括组长和组员
     * @param $group_type
     * @param $current_user
     * @return array
     */
	private function _getAdminsByGroupType($group_type){
        $this->db->select('a.id,a.account,a.name');
        $this->db->from($this->table.' a');
        $this->db->join('admin_group g','a.group_id=g.id','LEFT');
        //判断当前登陆的是超管还是销售管理员，销售管理员只能看到自己及其组员，超管可以看到所有销售组长和组员
        if($this->_user->role_id == '2' && $group_type == 1){  //role_id == 2 销售组长角色
            $this->db->where(array('g.type =' =>$group_type,'a.group_id ='=>$this->_user->group_id,'a.forbidden ='=>0));
        }else{
            $this->db->where(array('g.type =' =>$group_type,'a.forbidden ='=>0));
        }
        //$this->db->or_where('role_id =',1);
        $queryResult = $this->db->get()->result();
        $kvArr = array();
        foreach ($queryResult as $k=>$v){
            $kvArr[$v->id] = $v->account.'-'.$v->name;
        }
        return $kvArr;
    }
	private function _getRoleAdmins($role_id){
	    $this->db->select('id,account');
	    $this->db->from($this->table);
	    $this->db->where(array('role_id =' =>$role_id,'forbidden ='=>0));
	    $this->db->or_where('role_id =',1);
	    $queryResult = $this->db->get()->result();
	    $kvArr = array();
	    foreach ($queryResult as $k=>$v){
	        $kvArr[$v->id] = $v->account;
	    }
	    return $kvArr;
	}
	/**
	 * 管理员列表页总数量查询（为分页查询总页数）
	 * @param $name	管理员名（模糊匹配）
	 */
	/**
	 * 根据角色标识 取用户
	 * @param $role_id 角色标识
	 */
	public function getUserListByRoleId($role_id){
		$this->db->select('*');
		$this->db->from($this->table);
		$this->db->where('role_id', $role_id);
		return $this->db->get();
	}

	public function addAdmin($vo){
		if(isset($vo->password) && strlen($vo->password) > 0){
			$vo->salt = md5(time().rand(1, 10000));
			$vo->password = $this->useridentity->encodePassword($vo->password, $vo->salt);
		}else{
			unset($vo->password);
			unset($vo->salt);
		}
		return $this->add($vo);
	}
	public function updateAdmin($vo){
		if(isset($vo->password) && strlen($vo->password) > 0){
			$vo->salt = md5(time().rand(1, 10000));
			$vo->password = $this->useridentity->encodePassword($vo->password, $vo->salt);
		}else{
			unset($vo->password);
			unset($vo->salt);
		}
		return $this->update($vo);
	}
	/**
	 * 批量修改禁用状态
	 * @param $idTimeList ID=>update_time数组 {'id'=> 'update_time'...}
	 * @param $flg 禁用的值(1：禁用   0：启用)
	 */
	function changeForbidden($idTimeList, $flg){
		if(!is_array($idTimeList) || count($idTimeList) < 1){
			return false;
		}
		$currTime = time();
		$this->db->trans_start();
		foreach ($idTimeList as $id => $update_time){
			if(!$this->update((Object)Array('id'=>$id, 'update_time'=>$update_time, 'forbidden'=>$flg))){
				$this->db->_trans_status = FALSE;
				break;
			}
		}
		return $this->db->trans_complete();
	}
	/**
	 * 批量删除用户
	 * @param $idTimeList ID=>update_time数组 {'id'=> 'update_time'...}
	 */
	function deleteUser($idTimeList){
		if(!is_array($idTimeList) || count($idTimeList) < 1){
			return false;
		}
		$currTime = time();
		$this->db->trans_start();
		foreach ($idTimeList as $id => $update_time){
			if(!$this->db->delete($this->table, Array('id'=>$id, 'update_time'=>$update_time)) || ($this->db->affected_rows() < 1)){
				$this->db->_trans_status = FALSE;
				break;
			}
		}
		return $this->db->trans_complete();
	}
	/**
	 * 修改密码
	 * @param $user	用户信息
	 * @param $oldPwd	旧密码
	 * @param $newPwd	新密码
	 */
	function changePwd($user, $oldPwd, $newPwd){
		$oldPwd = $this->useridentity->encodePassword($oldPwd, $user->salt);
		$newSalt = md5(time().rand(1, 10000));
		$newPwd = $this->useridentity->encodePassword($newPwd, $newSalt);
		$this->db->set('password', $newPwd);
		$this->db->set('salt', $newSalt);
		$this->db->where('id', $user->id);
		$this->db->where('password', $oldPwd);
		$rtn = $this->db->update($this->table);
		return ($rtn === true) && ($this->db->affected_rows() == 1);
	}
	/**
	 * 登录成功后的动作
	 * @param $user 用户信息
	 */
	function recodeLogin(&$user){
		//记录IP和登录时间
		$this->db->set('last_login_time', time());
		$this->db->set('last_login_ip', $this->input->ip_address());
		$this->db->where('id', $user->id);
		$this->db->update($this->table);
	}
}
